//============================================================================
// Name        : image_manager.cpp
// Author      : dfoelber
//============================================================================

// INCLUDES //
#include "image_manager.h"
#include "graphics/graphics.h"
#include "draw/SDL_draw.h"
#include <iostream>
//////////////

ImageManager* ImageManager::instance = NULL;

/**
* Private constructor
**/
ImageManager::ImageManager()
{
	Surface* surface = new Surface();
			
	if( surface->LoadResource( "rc" ) )
	{
		map = surface;
	}
	else // error
	{
		delete surface;
	}
}

/**
* Deconstructor
**/
ImageManager::~ImageManager()
{
	for( int i = 0; i < (int)surfaces.size(); i++ )
	{
		delete surfaces[i];
		surfaces[i] = NULL;
	}
	
	if( instance != NULL )
	{
		delete instance;
	}
	
	if( map != NULL )
	{
		delete map;
	}
}

/**
* Singleton accessor
* 
* @return Singleton instance
**/
ImageManager* ImageManager::GetManager()
{
	if( instance == NULL )
	{
		instance = new ImageManager();
	}
	
	return instance;
}

/**
* Loads images into memory
**/
void ImageManager::LoadImages()
{
	for( int i = 0; i < NUM_IMAGES; i++ )
	{
		Surface* surface = NULL;
		
		surface = new Surface(
				SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA | SDL_SRCCOLORKEY, 
						IMAGE_MAPPING[i][2], IMAGE_MAPPING[i][3], 32, 0, 0, 0, 0));
		
		map->Apply(surface, IMAGE_MAPPING[i][0], IMAGE_MAPPING[i][1],
				IMAGE_MAPPING[i][2], IMAGE_MAPPING[i][3], 0, 0);
		
		if( i == 13 || i == 8 )
			SDL_SetAlpha(surface->GetSurface(), SDL_SRCALPHA, 100);
		
		surfaces.push_back( surface );
	}
}

/**
* Gets an image
* 
* @param id The image ID
* @param The surface
**/
Surface* ImageManager::GetImage( XYNE_IMAGE id )
{
	return surfaces[ id ];
}

/**
* Creates a new surface and returns it.
* 
* @param resolutionWidth Desired width to scale the image
* @param resolutionHeight Desired height to scale the image
* @param The surface
**/
Surface* ImageManager::CreateImage( int width, int height )
{
	SDL_Surface* created = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, 
			width, height, 32, 0, 0, 0, 0);
	
	Draw_FillRect(created, 0, 0, width, height, ALPHA_COLOR.ToUint32());
	SDL_SetColorKey(created, SDL_SRCCOLORKEY, ALPHA_COLOR.ToUint32());
	
	Surface* surface = NULL;
	
	if( created )
	{
		surface = new Surface(created);
		return surface;
	}
	
	return NULL;
}
